package pers.w.chaptertalk.reader;

import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.SeekBar;
import android.widget.Spinner;
import android.widget.TableLayout;
import android.widget.Toast;

import pers.w.chaptertalk.R;
import pers.w.chaptertalk.funs.Fun;
import pers.w.chaptertalk.tts.MainHandlerConstant;
import pers.w.chaptertalk.tts.util.AutoCheck;

class Spoken_Setting implements MainHandlerConstant {
    private ReaderActivity reader;
    private SeekBar sb_speed;
    private Spinner spinner_model;
    private TableLayout layout;
    private Synth spoken;
    private static String TAG = "spoken setting";
    private boolean playing = false;
    private CheckBox cb_countdown, cb_mobile_net;
    private Spinner spinner_countdown;
    private Button btn_play;

    Spoken_Setting(ReaderActivity activity) {
        reader = activity;
        layout = activity.findViewById(R.id.tl_spoken_setting);

        sb_speed = activity.findViewById(R.id.sb_spoken_speed);
        spinner_model = activity.findViewById(R.id.spinner_audio_model);
        cb_countdown = activity.findViewById(R.id.cb_countdown);
        cb_countdown.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked){
                int position = spinner_countdown.getSelectedItemPosition();
                initCountdown(reader.getResources().getIntArray(R.array.i_countdown_times)[position]);

            }
        });
        cb_mobile_net = activity.findViewById(R.id.cb_mobile_net);
        spinner_countdown = activity.findViewById(R.id.spinner_countdown);
        initButtons();
        sb_speed.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                int p = seekBar.getProgress();
                if (spoken != null && p != spoken.getSpeed()) {
                    spoken.setSpeed(p == 0 ? 1 : p); //改变语速
                    if (isPlaying()) {
                        stopSpoken(false);
                        startSpoken();
                    }
                }
            }
        });

        initSpinner();

        cb_mobile_net.setOnCheckedChangeListener((buttonView, isChecked) ->
                spoken.setUseMobileNet(isChecked));
    }

    private static String PAUSE = "暂停";
    private static String PLAY = "播放";

    private void initButtons() {
        Button.OnClickListener listener = v -> {
            switch (v.getId()) {
                case R.id.btn_stop_spoken:
                    stopSpoken(false);
                    break;
                case R.id.btn_play_spoken:
                    if (btn_play.getText().equals(PAUSE)) {
                        pause();
                    } else {
                        resume();
                    }
                    break;
            }
        };
        Button btn_stop = reader.findViewById(R.id.btn_stop_spoken);
        btn_stop.setOnClickListener(listener);
        btn_play = reader.findViewById(R.id.btn_play_spoken);
        btn_play.setText(PAUSE);
        btn_play.setOnClickListener(listener);
    }

    private void initSpinner() {
        AdapterView.OnItemSelectedListener spinner_listener = new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                switch (parent.getId()) {
                    case R.id.spinner_audio_model: //改变声音
                        if (position > 0 && position != spoken.getSpeaker()) {
                            if (spoken != null) {
                                Log.d(TAG, "onItemSelected: ");
                                spoken.setSpeaker(position);//0被占用了 “选择”,内部会自动-1
                                if (isPlaying()) {
                                    stopSpoken(false);
                                    startSpoken();
                                }
                            }
                        }
                        break;
                    case R.id.spinner_countdown:
                        initCountdown(reader.getResources().getIntArray(R.array.i_countdown_times)[position]);
                        break;
                }

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        };
        spinner_countdown.setSelection(1);//30分钟
        spinner_countdown.setOnItemSelectedListener(spinner_listener);
        spinner_model.setOnItemSelectedListener(spinner_listener);
    }

    boolean isPlaying() {
        return playing;
    }

    boolean isVisibility() {
        return layout.getVisibility() == View.VISIBLE;
    }

    private void show() {
        layout.startAnimation(reader.ltoC);
        layout.setVisibility(View.VISIBLE);
    }

    private void setUI() {
        sb_speed.setProgress(spoken.getSpeed());
        spinner_model.setSelection(spoken.getSpeaker());
        cb_mobile_net.setChecked(spoken.isUseMobileNet());
        play();
        playNextPage();//预加载下一页，不然太生硬
    }

    void play(String text) {
        spoken.speak(text);
    }

    void play() {
        // for (int i = reader.control.getCurPageIndex(); playing && i < reader.control.getPagesSize(); i++) {
        ReaderControl.TextPage page = reader.control.getCurPage();// reader.control.getPage(i);
        int startIndex = 0;//继续从上一次的位置开始播放
        if (curPageSpokenProgress != 0 /*&& i == reader.control.getCurPageIndex() */) {
            startIndex = curPageSpokenProgress;
            startIndex = Math.max(startIndex - 15, 0);//往回走10个字播放，但是不能小于起始位置
            startIndex = Math.min(startIndex, page.end - page.start - 1);//避免偏移量超过字符数
            pageOffset = startIndex;
        }

        spoken.speak(reader.chapter.getContent().substring(page.start + startIndex, page.end));
        //}
    }

    void playNextPage() {
        int index = reader.control.getCurPageIndex();
        if (index + 1 < reader.control.getPagesSize()) {
            ReaderControl.TextPage page = reader.control.getPage(index + 1);// reader.control.getPage(i);
            spoken.speak(reader.chapter.getContent().substring(page.start, page.end));
        }
    }

    private void hide() {
        layout.startAnimation(reader.ctoL);
        layout.setVisibility(View.INVISIBLE);
    }

    public void setVisibility(boolean show) {
        layout.setVisibility(show ? View.VISIBLE : View.INVISIBLE);
    }

    /**
     * 停止听书，
     *
     * @param release 是否释放资源
     */
    void stopSpoken(boolean release) {
        playing = false;
        reader.pb_loading.setVisibility(View.INVISIBLE);
        reader.service.removeNotification(reader);//能销毁activity的时候，肯定解绑了
        reader.control.update_SQL(reader.book.getID());
        btn_play.setText(PAUSE);//结束播放的时候把播放按钮还原，否则再次启动听书，无法控制
        cb_countdown.setChecked(false);
        if (spoken != null) {
            spoken.stop();
            if (release) {
                spoken.release();
                spoken = null;
            }
        }
        hide();

    }

    void startSpoken() {
        Toast.makeText(reader, R.string.spoken_loading, Toast.LENGTH_LONG).show();
        reader.pb_loading.setVisibility(View.VISIBLE);
        reader.service.createNotification(reader);
        playing = true;
        show();
        if (null == spoken) {
            new Thread(() -> spoken = new Synth(reader, mainHandler, checkHandle)).start();
        } else
            setUI();
    }

    void pause() {
        if (reader.service.pause()){
            spoken.pause();
            btn_play.setText(PLAY);
        }
    }

    void resume() {
        if (reader.service.resume()){
            spoken.resume();
            btn_play.setText(PAUSE);
        }
    }

    public void setCurPageSpokenProgress() {
        this.curPageSpokenProgress = 0;
        pageOffset = 0;
    }

    private boolean title = false;

    public void setTitle() {
        this.title = true;
    }

    private int curPageSpokenProgress = 0;
    private int pageOffset = 0;//这个变量只是在首次判断是否要翻页的时候计算，因为启动页不一定是从0开始读，判断一次后就归零
    private Handler mainHandler = new Handler(msg -> {
        //  Log.d(TAG, ": " + msg);
        switch (msg.what) {
            case PRINT:
                String printStr = (String) msg.obj;
                if (printStr.indexOf("初始化成功") > 0) {
                    setUI();
                }
                if (printStr.indexOf("播放结束回调") == 0) {
                    if (title) {
                        title = false;
                        break;
                    }
                    reader.page_turning(true);
                }
                break;

            case INIT_SUCCESS:
                break;
            case UI_CHANGE_INPUT_TEXT_SELECTION:
                //  ReaderControl.TextPage page = reader.control.getCurPage();
                //  String curContent = reader.tv_reader.getText().toString();
                //    int length =  curContent.length();
//                for (; length >0 ; ) {//计算字数不能把空格和换行符计算进去，否则可能不会翻页
//                    char c = curContent.charAt(length - 1);
//                    if (String.valueOf(c).matches("[\u4e00-\u9fa5]")) {//匹配最后一个汉字
//                        //length--;提前一个字翻页
//                        break;
//                    } else
//                        length--;
//                }
                if (pageOffset > 0) {
                    msg.arg1 += pageOffset;
                }
                //    Log.d(TAG, "UI_CHANGE_INPUT_TEXT_SELECTION: " + msg.arg1 +"/"+length);

//                if (msg.arg1 >= length/* page.end - page.start*/) {
//                   // reader.page_turning(true);
//                }else {
//                     curPageSpokenProgress = msg.arg1;
//                }
                curPageSpokenProgress = msg.arg1;
                break;
        }
        return false;
    });
    private Handler checkHandle = new Handler(msg -> {
        if (msg.what == 100) {
            AutoCheck autoCheck = (AutoCheck) msg.obj;
            synchronized (autoCheck) {
                String message = autoCheck.obtainDebugMessage();
                if (Fun.isDebug()) Log.d(TAG, message); // 可以用下面一行替代，在logcat中查看代码
                // Log.w("AutoCheckMessage", message);
            }
        }
        return false;
    });

    private int countdown;

    void spokenCountdown() {
        if (playing && cb_countdown.isChecked()) {

            //int t = Integer.parseInt(et_countdown.getText().toString());
            if (Fun.isDebug()) Log.d(TAG, "spokenCountdown: " + countdown);
            if (--countdown <= 0) {
                stopSpoken(false);
                if (!reader.hasWindowFocus()) reader.setScreenOn(false);//听书结束的时候，判断一下是否在后台运行，在后台就不再阻止后台休眠
                cb_countdown.setChecked(false);
            } else {
                cb_countdown.setText(String.format(reader.getString(R.string.spoken_countdown), countdown / 60, countdown % 60));
            }
        }
    }

    private void initCountdown(int second) {
        countdown = second;
        cb_countdown.setText(String.format(reader.getString(R.string.spoken_countdown), countdown / 60, countdown % 60));

    }


}
